package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.CategoryActivity;
import com.gongpingjialoan.activity.search.CityActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.ApiSecurity;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.CheckOnsiteData;
import com.gongpingjialoan.bean.CheckShopData;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.view.widget.DateChooseWheelViewDialog;
import com.gongpingjialoan.widget.LoadingDialog;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 预约检测
 * Created by huangcg on 2017/5/11.
 */
public class CarOrderCheckActivity extends BaseActivity implements View.OnClickListener {

    private static final int SHOP_STATE = 1;
    private static final int ONSITE_STATE = 2;
    private TextView shop_check_txt, onsite_check_txt, check_verifycode_tv;
    private EditText check_name_et, check_phone_et, verifycode_et;
    private RelativeLayout check_city_rl, check_brand_rl, check_time_rl;
    private TextView check_city_tv, check_brand_tv, check_time_tv,check_title_tv;
    private TextView check_order_button;
    private LinearLayout check_data_ll,verifycode_ll,check_ll;
    private final int REQUEST_CITY_FRAGMENT = 1;
    private final int REQUEST_BRAND = 2;
    private String mModelName;
    private NetDataJson mNetDataJson;
    private NetDataJson mGetVCodeNetDataJson;
    private String city;
    private int reserve_type = SHOP_STATE;
    private boolean isCountRunning;
    private NetDataJson mSubmitNetDataJson;
    private String dealer_id = "";
    private String mBrandName;
    private int selectPosition =0;
    private List<CheckShopData.DataBean> mShopdatadata = new ArrayList<>();
    private  List<CheckOnsiteData.DataBean> mCheckOnsiteDataBean = new ArrayList<>();
    private LoadingDialog loadingPb;
    private DateChooseWheelViewDialog startDateChooseDialog;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_check_car);
        PointRecordManage.getInstance().addPoint(mySelf, Piont.DetectionView);
        initView();
        initData();
    }

    private void initData() {
        if("SecondDetailFragment".equals(getIntent().getStringExtra("comeFrom"))){
            mBrandName = getIntent().getStringExtra("brand");
            mModelName = getIntent().getStringExtra("model");
            city = getIntent().getStringExtra("city");
            check_brand_tv.setText(mModelName);
            check_brand_rl.setClickable(false);
            check_city_rl.setClickable(false);
        }else{
            city = MainActivity.main.currentCity;
        }
        if (GPJApplication.getInstance().isLogin()) {
            check_phone_et.setText(getMyPhone());
        }
        setTitle("预约检测");
        check_city_tv.setText(city);
        getSellerData();
    }


    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }


    private void initView() {
        shop_check_txt = (TextView) findViewById(R.id.shop_check_txt);
        onsite_check_txt = (TextView) findViewById(R.id.onsite_check_txt);
        check_verifycode_tv = (TextView) findViewById(R.id.check_verifycode_tv);
        check_city_tv = (TextView) findViewById(R.id.check_city_tv);
        check_brand_tv = (TextView) findViewById(R.id.check_brand_tv);
        check_time_tv = (TextView) findViewById(R.id.check_time_tv);
        check_name_et = (EditText) findViewById(R.id.check_name_et);
        check_phone_et = (EditText) findViewById(R.id.check_phone_et);
        verifycode_et = (EditText) findViewById(R.id.verifycode_et);
        check_city_rl = (RelativeLayout) findViewById(R.id.check_city_rl);
        check_brand_rl = (RelativeLayout) findViewById(R.id.check_brand_rl);
        check_time_rl = (RelativeLayout) findViewById(R.id.check_time_rl);
        verifycode_ll= (LinearLayout) findViewById(R.id.verifycode_ll);
        check_order_button = (TextView) findViewById(R.id.check_order_button);
        check_data_ll = (LinearLayout) findViewById(R.id.check_data_ll);
        check_ll = (LinearLayout) findViewById(R.id.check_ll);
        check_title_tv = (TextView) findViewById(R.id.check_title_tv);
        shop_check_txt.setOnClickListener(this);
        onsite_check_txt.setOnClickListener(this);
        check_verifycode_tv.setOnClickListener(this);
        check_city_rl.setOnClickListener(this);
        check_brand_rl.setOnClickListener(this);
        check_time_rl.setOnClickListener(this);
        check_order_button.setOnClickListener(this);
        check_phone_et.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if (check_phone_et.getText().length() == 11) {
                    if (isMyPhone(check_phone_et.getText().toString()) && GPJApplication.getInstance().isLogin()) {
                        verifycode_ll.setVisibility(View.GONE);
                    } else {
                        verifycode_ll.setVisibility(View.VISIBLE);
                        if (!isCountRunning) {
                            check_verifycode_tv.setEnabled(true);
                        }
                    }
                } else {
                    verifycode_ll.setVisibility(View.VISIBLE);
                    check_verifycode_tv.setEnabled(false);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });


    }

    @Override
    protected void onDestroy() {
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
        }
        if (mGetVCodeNetDataJson != null) {
            mGetVCodeNetDataJson.cancelTask();
        }
        if (mSubmitNetDataJson != null) {
            mSubmitNetDataJson.cancelTask();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shop_check_txt:
                if(reserve_type == SHOP_STATE)return;
                reserve_type = SHOP_STATE;
                shop_check_txt.setTextColor(getResources().getColor(R.color.button_normal_color));
                onsite_check_txt.setTextColor(getResources().getColor(R.color.discount_title));
                getSellerData();
                break;
            case R.id.onsite_check_txt:
                if(reserve_type == ONSITE_STATE)return;
                reserve_type = ONSITE_STATE;
                shop_check_txt.setTextColor(getResources().getColor(R.color.discount_title));
                onsite_check_txt.setTextColor(getResources().getColor(R.color.button_normal_color));
                getSellerData();
                break;
            case R.id.check_verifycode_tv:
                getVergifyCode();
                break;
            case R.id.check_brand_rl:
                Intent intent = new Intent();
                intent.setClass(this, CategoryActivity.class);
                intent.putExtra("needModelDetailFragment", false);
                startActivityForResult(intent, REQUEST_BRAND);
                break;
            case R.id.check_city_rl:
                Intent i = new Intent();
                i.putExtra("needProvince", false);
                i.setClass(this, CityActivity.class);
                startActivityForResult(i, REQUEST_CITY_FRAGMENT);
                break;
            case R.id.check_time_rl:
                showTimeDialog();
                break;
            case R.id.check_order_button:
                submitOrder();
            default:
                break;
        }
    }

    private void showTimeDialog() {
        if(startDateChooseDialog == null){
            startDateChooseDialog = new DateChooseWheelViewDialog(CarOrderCheckActivity.this, new DateChooseWheelViewDialog.DateChooseInterface() {
                @Override
                public void getDateTime(String time, boolean longTimeChecked) {
                    check_time_tv.setText(time);
                }
            });
        }

        startDateChooseDialog.setDateDialogTitle("预约时间");
        startDateChooseDialog.showDateChooseDialog();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 城市选择回调
                case REQUEST_CITY_FRAGMENT:
                    Bundle b = data.getExtras();
                    city = b.getString("city");
                    if (!TextUtils.isEmpty(city)) {
                        check_city_tv.setText(city);
                    }
                    getSellerData();
                    break;

                // 车型选择回调
                case REQUEST_BRAND:
                    Bundle bundle = data.getExtras();
                    mBrandName = bundle.getString("brandName");
                    mModelName = bundle.getString("modelName");
                    check_brand_tv.setText( mModelName);
                    break;
            }
        }
    }

    private void getSellerData() {
        mNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                showTips(4,errorMessage);
                check_order_button.setEnabled(false);
                check_ll.setVisibility(View.GONE);
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                Gson gson = new Gson();
                check_data_ll.removeAllViews();
                 if(reserve_type == SHOP_STATE){
                     CheckShopData checkShopData = gson.fromJson(json.toString(), CheckShopData.class);
                      mShopdatadata = checkShopData.getData();
                     int size = mShopdatadata.size();
                     if(size > 0){
                         check_ll.setVisibility(View.VISIBLE);
                         for (int i = 0; i <size; i++) {
                             CheckShopData.DataBean source = mShopdatadata.get(i);
                             View view = LayoutInflater.from(CarOrderCheckActivity.this).inflate(R.layout.order_check_car_item, null);
                             final ImageView checkImg = (ImageView) view.findViewById(R.id.check_img);
                             view.setTag(i);
                             ImageView car_img = (ImageView) view.findViewById(R.id.car_img);
                             TextView price_by_num_tv = (TextView) view.findViewById(R.id.price_by_num_tv);
                             TextView price_by_day_tv = (TextView) view.findViewById(R.id.price_by_day_tv);
                             price_by_day_tv.setMaxLines(2);
                             if(source != null){
                                 if(!TextUtils.isEmpty(source.getCompany())){
                                     price_by_num_tv.setText(source.getCompany());
                                     price_by_num_tv .setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                                 }
                                 if(!TextUtils.isEmpty(source.getAddress())){
                                     price_by_day_tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                                     price_by_day_tv.setTextColor(getResources().getColor(R.color.discount_price_title));
                                     price_by_day_tv.setText(source.getAddress());
                                 }
                             Glide.with(CarOrderCheckActivity.this).load(source.getImg()).placeholder(R.drawable.icon_jiancedian).error(R.drawable.icon_jiancedian).into(car_img);
                             }
                             if(i == 0) checkImg.setSelected(true);
                             view.setOnClickListener(new View.OnClickListener() {
                                 @Override
                                 public void onClick(View v) {
                                     selectPosition = (int)v.getTag();
                                     checkSubmitStatus();
                                     int count = check_data_ll.getChildCount();
                                     for (int j = 0; j < count; j++) {
                                         View view = check_data_ll.getChildAt(j);
                                         ImageView checkImg0 =  (ImageView)view.findViewById(R.id.check_img);

                                         if(j == selectPosition){
                                             checkImg0.setSelected(true);
                                         }else{
                                             checkImg0.setSelected(false);
                                         }
                                     }
                                 }
                             });
                             check_data_ll.addView(view);
                         }
                         check_title_tv.setText("检测点地址");
                     }else{
                         check_ll.setVisibility(View.GONE);
                     }

                 }else{
                     CheckOnsiteData checkOnsiteData = gson.fromJson(json.toString(), CheckOnsiteData.class);
                     mCheckOnsiteDataBean = checkOnsiteData.getData();
                     int size = mCheckOnsiteDataBean.size();
                     if(size > 0){
                         check_ll.setVisibility(View.VISIBLE);
                         for (int i = 0; i <size; i++) {
                             CheckOnsiteData.DataBean source = mCheckOnsiteDataBean.get(i);
                             View view = LayoutInflater.from(CarOrderCheckActivity.this).inflate(R.layout.order_check_car_item, null);
                             ImageView checkImg = (ImageView) view.findViewById(R.id.check_img);
                             ImageView car_img = (ImageView) view.findViewById(R.id.car_img);
                             TextView price_by_num_tv = (TextView) view.findViewById(R.id.price_by_num_tv);
                             TextView price_by_day_tv = (TextView) view.findViewById(R.id.price_by_day_tv);
                             checkImg.setVisibility(View.GONE);
                             if(source != null){
                                 if(!TextUtils.isEmpty(source.getCharge_info().getCar()))
                                     price_by_num_tv.setText("按辆收费:" + source.getCharge_info().getCar());
                                 if(!TextUtils.isEmpty(source.getCharge_info().getTime()))
                                     price_by_day_tv.setText("按时收费:" + source.getCharge_info().getTime());
                                 Glide.with(CarOrderCheckActivity.this).load(source.getImg()).placeholder(R.drawable.no_pic).error(R.drawable.no_pic).into(car_img);
                             }
                             check_data_ll.addView(view);
                         }
                         check_title_tv.setText("合作平台及收费标准");
                     }else{
                         check_ll.setVisibility(View.GONE);
                     }
                 }
                checkSubmitStatus();
            }
        });
        mNetDataJson.addParam("city", city);
        mNetDataJson.addParam("reserve_type", reserve_type+"");
        mNetDataJson.setUrl(API.get_seller_data);
        mNetDataJson.request("get");
    }

    private void checkSubmitStatus() {
        dealer_id = "";
        if(reserve_type == SHOP_STATE){
            if(mShopdatadata.size() >0){
                dealer_id = mShopdatadata.get(selectPosition).getId() +"";
            }
        }else{
            for(CheckOnsiteData.DataBean data: mCheckOnsiteDataBean){
                if(data.getId().contains("273")){
                    dealer_id = data.getId();
                    break;
                }
            }

            if(TextUtils.isEmpty(dealer_id)){
                StringBuilder sb = new StringBuilder();
                int size = mCheckOnsiteDataBean.size();
                if(size > 0){
                    for (int i = 0; i <size-1;i++){
                        sb.append(mCheckOnsiteDataBean.get(i).getId()).append("-");
                    }
                    sb.append(mCheckOnsiteDataBean.get(size-1).getId());
                }
                dealer_id = sb.toString();
            }
        }
        if(TextUtils.isEmpty(dealer_id)){
            if(reserve_type == SHOP_STATE){
                check_order_button.setText("暂无检测点");
            }else{
                check_order_button.setText("暂无合作平台");
            }
            check_order_button.setEnabled(false);
        }else{
            check_order_button.setText("立即预约");
            check_order_button.setEnabled(true);
        }
    }

    private void getVergifyCode() {
        check_verifycode_tv.setEnabled(false);
        isCountRunning = true;
        new CountDownTimer(Const.CODE_TIME * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                check_verifycode_tv.setText(millisUntilFinished / 1000 + "秒");

            }

            @Override
            public void onFinish() {
                isCountRunning = false;
                if (check_phone_et.getText().length() == 11) {
                    if(isMyPhone(check_phone_et.getText().toString()) && GPJApplication.getInstance().isLogin()){
                        verifycode_ll.setVisibility(View.GONE);
                    }else{
                        check_verifycode_tv.setEnabled(true);
                        verifycode_ll.setVisibility(View.VISIBLE);

                    }
                }
                check_verifycode_tv.setText("重新发送");
            }
        }.start();
        mGetVCodeNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonUpdate(JSONObject json) {
            }

            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(CarOrderCheckActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
        String url = "/mobile/api/get-captcha/";
        mGetVCodeNetDataJson.addParam("phone", check_phone_et.getText().toString());
        mGetVCodeNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mGetVCodeNetDataJson.addParam("sign", ApiSecurity.security(GPJApplication.getInstance().getSecert(),check_phone_et.getText().toString()));
        mGetVCodeNetDataJson.setUrl(url);
        mGetVCodeNetDataJson.request("post");
    }

    private boolean isMyPhone(String phone){
        return phone.equals(getMyPhone());
    }
    private String getMyPhone(){
        return new UserManager().LoadUserInfo().getPhone();
    }
    private void submitOrder() {
        if(reserve_type == SHOP_STATE){
            PointRecordManage.getInstance().addPoint(mySelf, Piont.DetectionDealerAppointmentClick);
        }else {
            PointRecordManage.getInstance().addPoint(mySelf, Piont.DetectionHomeAppointmentClick);
        }
        String contact = check_name_et.getText().toString();
        if(TextUtils.isEmpty(contact)){
            showTips(2,"请填写您的姓名");
            return;
        }
        if(TextUtils.isEmpty(city)){
            showTips(2,"请选择城市");
            return;
        }
        if(TextUtils.isEmpty(mBrandName) ||TextUtils.isEmpty(mModelName)){
            showTips(2,"请选择车型");
            return;
        }

        String reserve_time = check_time_tv.getText().toString();
        if(TextUtils.isEmpty(reserve_time)){
            showTips(2,"请选择时间");
            return;
        }
        String phone = check_phone_et.getText().toString();
        if(TextUtils.isEmpty(phone)){
            showTips(2,"请输入手机号码");
            return;
        }
        String captcha = null;
        if(!isMyPhone(phone) || !GPJApplication.getInstance().isLogin()){
             captcha = verifycode_et.getText().toString();
            if(TextUtils.isEmpty(captcha)){
                showTips(2,"请输入验证码");
                return;
            }
        }

        mSubmitNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                if(reserve_type == SHOP_STATE){
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.DetectionDealerAppointmentSuccess);
                }else {
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.DetectionHomeAppointmentSuccess);
                }
                Toast.makeText(CarOrderCheckActivity.this, "预约成功", Toast.LENGTH_SHORT).show();
                hidenProgressDialog();
                finish();
            }

            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
                Toast.makeText(CarOrderCheckActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
        mSubmitNetDataJson.addParam("contact", contact);
        mSubmitNetDataJson.addParam("city", city);
        mSubmitNetDataJson.addParam("brand", mBrandName);
        mSubmitNetDataJson.addParam("model", mModelName);

        mSubmitNetDataJson.addParam("reserve_time", reserve_time.replace("时",""));
        mSubmitNetDataJson.addParam("phone", phone);
        if(!isMyPhone(phone) || !GPJApplication.getInstance().isLogin())mSubmitNetDataJson.addParam("captcha", captcha);
        mSubmitNetDataJson.addParam("reserve_type", reserve_type);
        mSubmitNetDataJson.addParam("dealer_id", dealer_id);
        mSubmitNetDataJson.setUrl(API.add_reserve_detection);
        mSubmitNetDataJson.request("post");
        showProgressDialog();
    }

    public void showProgressDialog() {
        if (!isFinishing()) {
            if (loadingPb == null) {
                loadingPb = new LoadingDialog(this);
            }
            loadingPb.show();
        }
    }

    public void hidenProgressDialog() {
        if (!isFinishing()) {
            if (loadingPb != null) {
                loadingPb.dismiss();
            }
        }
    }
}
